/**
 * @file producer_example.cpp
 * @brief MessageFramework生产者示例
 *
 * 展示如何使用MessageProducer发送交易信号和API请求
 */

#include "MessageProducer.h"
#include "SignatureHelper.h"
#include "handlers/TradeSignalHandler.h"
#include "handlers/APIRequestHandler.h"
#include "RedisPool.h"
#include <spdlog/spdlog.h>
#include <iostream>

using namespace MessageFramework;

int main() {
    spdlog::set_level(spdlog::level::debug);

    // 1. 初始化Redis连接池
    RedisPool::Config redisConfig;
    redisConfig.host = "127.0.0.1";
    redisConfig.port = 6379;
    redisConfig.password = "redis_EX7Nms";
    redisConfig.poolSize = 5;

    RedisPool* redisPool = RedisPool::getInstance();
    redisPool->init(redisConfig);

    // 2. 创建消息生产者
    MessageProducer::Config producerConfig;
    producerConfig.publisherId = "StrategyEngine-1";
    producerConfig.secretKey = "your-secret-key-32bytes-long!!!";  // 32字节密钥
    producerConfig.autoSign = true;
    producerConfig.autoEncrypt = false;  // 演示不加密

    MessageProducer producer(redisPool, producerConfig);

    // ==================== 示例1：发送交易信号 ====================
    std::cout << "\n=== 发送交易信号示例 ===\n" << std::endl;

    TradingSignalBody signal;
    std::strcpy(signal.instrumentId, "rb2501");
    std::strcpy(signal.direction, "BUY");
    std::strcpy(signal.offsetFlag, "OPEN");
    signal.price = 4000.0;
    signal.volume = 1;
    std::strcpy(signal.orderType, "LIMIT");
    std::strcpy(signal.strategyId, "MA_Crossover_Strategy");
    std::strcpy(signal.comment, "金叉做多信号");

    std::string streamId = producer.send(
        "trading_signals",          // 目标Stream
        "TradeSignal",              // 消息类型
        signal.toJson(),            // 消息体
        ""                          // consumerId为空表示广播
    );

    if (!streamId.empty()) {
        std::cout << "✅ 交易信号发送成功！Stream ID: " << streamId << std::endl;
        std::cout << "   合约: " << signal.instrumentId << std::endl;
        std::cout << "   方向: " << signal.direction << " " << signal.offsetFlag << std::endl;
        std::cout << "   价格: " << signal.price << std::endl;
        std::cout << "   数量: " << signal.volume << std::endl;
    } else {
        std::cout << "❌ 交易信号发送失败！" << std::endl;
    }

    // ==================== 示例2：发送API请求 ====================
    std::cout << "\n=== 发送API请求示例 ===\n" << std::endl;

    APIRequestBody request;
    std::strcpy(request.requestType, "QUERY_ACCOUNT");
    std::strcpy(request.userId, "11440");
    std::strcpy(request.params, "{}");

    std::string requestStreamId = producer.sendRequest(
        "api_requests",                     // 目标Stream
        "APIRequest",                       // 消息类型
        request.toJson(),                   // 消息体
        "api_responses:req_12345",          // 响应Stream
        "TraderManager-1"                   // 指定接收者
    );

    if (!requestStreamId.empty()) {
        std::cout << "✅ API请求发送成功！Stream ID: " << requestStreamId << std::endl;
        std::cout << "   请求类型: " << request.requestType << std::endl;
        std::cout << "   用户ID: " << request.userId << std::endl;
        std::cout << "   响应Stream: api_responses:req_12345" << std::endl;
    } else {
        std::cout << "❌ API请求发送失败！" << std::endl;
    }

    // ==================== 示例3：发送加密消息 ====================
    std::cout << "\n=== 发送加密消息示例 ===\n" << std::endl;

    // 更新配置启用加密
    producerConfig.autoEncrypt = true;
    producerConfig.encryptionKey = EncryptionHelper::generateKey();  // 生成32字节密钥
    producer.updateConfig(producerConfig);

    std::cout << "🔑 加密密钥（请保存）: " << producerConfig.encryptionKey << std::endl;

    std::string encryptedStreamId = producer.send(
        "trading_signals",
        "TradeSignal",
        signal.toJson(),
        ""
    );

    if (!encryptedStreamId.empty()) {
        std::cout << "✅ 加密消息发送成功！Stream ID: " << encryptedStreamId << std::endl;
    } else {
        std::cout << "❌ 加密消息发送失败！" << std::endl;
    }

    // ==================== 示例4：分布式追踪 ====================
    std::cout << "\n=== 分布式追踪示例 ===\n" << std::endl;

    // 设置追踪上下文
    std::string traceId = MessageHeader::generateTraceId();
    producer.setTraceContext(traceId, "");

    std::cout << "🔍 TraceID: " << traceId << std::endl;

    // 发送第一条消息
    std::string msg1Id = producer.send("trading_signals", "TradeSignal", signal.toJson());

    // 发送第二条消息（属于同一个调用链）
    std::string msg2Id = producer.send("trading_signals", "TradeSignal", signal.toJson());

    std::cout << "✅ 两条消息属于同一个调用链（TraceID相同）" << std::endl;
    std::cout << "   消息1 ID: " << msg1Id << std::endl;
    std::cout << "   消息2 ID: " << msg2Id << std::endl;

    std::cout << "\n✅ 所有示例执行完成！" << std::endl;

    return 0;
}
